define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'goods/goods/index' + location.search,
                    add_url: 'goods/goods/add',
                    edit_url: 'goods/goods/edit',
                    del_url: 'goods/goods/del',
                    multi_url: 'goods/goods/multi',
                    import_url: 'goods/goods/import',
                    table: 'goods',
                }
            });
            $(".btn-add").data("area", ["100%", "100%"]);

            var table = $("#table");
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area", ["100%", "100%"]);
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Cn name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'en_name', title: __('En name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'code', title: __('Code'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'image', title: __('Image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                      //  {field: 'images', title: __('Images'), operate: false, events: Table.api.events.image,
                        //  formatter: Table.api.formatter.images},
                        {field: 'category_id', title: __('Category'),addClass:'selectpage',
                            extend:'data-source="goods/goods_category/index"',
                            formatter: function (value,row) {return row.category_name}},
                        {field: 'price', title: __('Price'), operate:'BETWEEN'},
                        // {field: 'virtual_sales', title: __('Virtual_sales'),operate: false},
                        // {field: 'real_sales', title: __('Real_sales')},
                        {field: 'status', title: __('Status'), searchList: {"200":__('Normal'),
                                "100":__('Hidden')}, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                     //   {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange',
                        //   autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });


            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'goods/goods/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'goods/goods/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'goods/goods/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {


            $(document).on('click', '.attr-add', function() {
                $(this).next().next().append(attr_html);
            });

            $(document).on('click', '.del-attr', function() {
                $(this).parent().remove();
            });
            $(document).on('click', '.sku-del', function() {
                $(this).parent().parent().remove();
            });
            $(document).on('click', '.sku-add', function() {
                $('#sku').append(sku_html)
            });

            Form.api.bindevent($("form[role=form]"), function () {
            }, function () {
            }, function (success, error) {
                    const skus = [];

                    $('.form-group').each(function() {
                        const skuName = $(this).find('.sku-name').val();
                        const attributes = [];

                        $(this).find('.attr-input').each(function() {
                            const attrCnName = $(this).find('input[name="attr_cn_name[]"]').val();
                            const attrEnName = $(this).find('input[name="attr_en_name[]"]').val();
                            const attrPrice = $(this).find('input[name="attr_price[]"]').val();

                            // 检查属性值是否都存在
                            if (attrCnName || attrEnName) {
                                attributes.push({
                                    cn_name: attrCnName ?? '', // 可以根据需要调整
                                    en_name: attrEnName ?? '', // 可以根据需要调整
                                    price: attrPrice ?? 0// 价格作为值
                                });
                            }
                        });

                        // 确保 SKU 名称和属性都存在
                        if (skuName && attributes.length > 0) {
                            skus.push({
                                sku_name: skuName,
                                attributes: attributes
                            });
                        }
                    });
                    $('input[name=sku]').val(JSON.stringify(skus))

                    Form.api.submit($("form[role=form]"), function (data, ret) {
                        parent.$("a.btn-refresh").trigger("click");
                        if(ret.code == 1){
                            parent.$("a.btn-refresh").trigger("click");
                            setTimeout(function(){
                                location.reload()
                            },1000)
                        }
                    });
                    Layer.close(index);

                return false;

            });

        },
        edit: function () {

            $(document).on('click', '.attr-add', function() {
                $(this).next().next().append(attr_html);
            });

            $(document).on('click', '.del-attr', function() {
                $(this).parent().remove();
            });
            $(document).on('click', '.sku-del', function() {
                $(this).parent().parent().remove();
            });
            $(document).on('click', '.sku-add', function() {
                $('#sku').append(sku_html)
            });

            Form.api.bindevent($("form[role=form]"), function () {
            }, function () {
            }, function (success, error) {
                const skus = [];

                $('.form-group').each(function() {
                    const skuName = $(this).find('.sku-name').val();
                    const attributes = [];

                    $(this).find('.attr-input').each(function() {
                        const attrCnName = $(this).find('input[name="attr_cn_name[]"]').val();
                        const attrEnName = $(this).find('input[name="attr_en_name[]"]').val();
                        const attrPrice = $(this).find('input[name="attr_price[]"]').val();

                        // 检查属性值是否都存在
                        if (attrCnName || attrEnName ) {
                            attributes.push({
                                cn_name: attrCnName ?? '', // 可以根据需要调整
                                en_name: attrEnName ?? '', // 可以根据需要调整
                                price: attrPrice ?? 0// 价格作为值
                            });
                        }
                    });

                    // 确保 SKU 名称和属性都存在
                    if (skuName && attributes.length > 0) {
                        skus.push({
                            sku_name: skuName,
                            attributes: attributes
                        });
                    }
                });
                $('input[name=sku]').val(JSON.stringify(skus))
                Form.api.submit($("form[role=form]"), function (data, ret) {
                    if(ret.code == 1){
                        parent.$("a.btn-refresh").trigger("click");
                        setTimeout(function(){
                            location.reload()
                        },1000)
                    }
                });
                Layer.close(index);

                return false;

            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };

    var attr_html = ' <div class="attr-input">\n' +
        '                        <input type="text" name="attr_cn_name[]"  class="form-control cy-input" value=""\n' +
        '                               placeholder="Cn name"  >\n' +
        '                        <input type="text" name="attr_en_name[]"  class="form-control cy-input" value=""\n' +
        '                               placeholder="en name"  >\n' +
        '                        <input type="text" name="attr_price[]"  class="form-control cy-input" value=""\n' +
        '                               placeholder="Price"  >\n' +
        '                         <span style="font-size: 30px;cursor: pointer" class="del-attr">-</span>\n' +
        '                    </div>'


    var sku_html = '        <div class="form-group">\n' +
        '            <label class="control-label col-xs-12 col-sm-2">Attr</label>\n' +
        '            <div class="col-xs-12 col-sm-8">\n' +
        '                <input  data-rule="" class="form-control sku-name"\n' +
        '                        name="attr_name[]" type="text" value="" placeholder="Attr name" style="width: 200px;">\n' +
        '                <a href="javascript:;" class="btn btn-success attr-add" >\n' +
        '                    Add Attr</a>\n' +
        '                <a href="javascript:;" class="btn btn-danger sku-del btn-disabled"  >\n' +
        '                    Delete</a>\n' +
        '                <div >\n' +
        '                    <div class="attr-input">\n' +
        '                        <input type="text" name="attr_cn_name[]"  class="form-control cy-input" value=""\n' +
        '                               placeholder="Cn name"  >\n' +
        '                        <input type="text" name="attr_en_name[]"  class="form-control cy-input" value=""\n' +
        '                               placeholder="en name"  >\n' +
        '                        <input type="text" name="attr_price[]"  class="form-control cy-input" value=""\n' +
        '                               placeholder="Price"  >\n' +
        '                         <span style="font-size: 30px;cursor: pointer" class="del-attr">-</span>\n' +
        '                    </div>\n' +
        '                </div>\n' +
        '            </div>\n' +
        '        </div>';
    return Controller;
});
